<script lang="ts" setup>
import {add, del, getList, update} from '@/api/ingredient-api'
import {onMounted, reactive, ref} from "vue";
import {type ComponentSize, ElMessage} from 'element-plus'
import axios from "axios";
import {uploadAddress} from '@/api/globe-config'
const currentPage = ref(1)
const pageSize = ref(20)
const pageTotal = ref(10000)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

const formInline = reactive({
  name: ''
})

const onSubmit = () => {
  console.log('submit!')
}

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  pageSize.value = val
  search()
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  if ((pageSize.value * (currentPage.value - 1)) < pageTotal.value) {
    currentPage.value = val
    search()
  }
}
const removeOne = (val) => {
  del(val)
      .then(res => {
        console.log(res)
        if (res.data.success) {
          ElMessage({
            type: "success",
            message: "删除成功"
          })
          search()
        } else {
          ElMessage({
            type: "error",
            message: "删除失败"
          })
        }
      })
}
const search = () => {
  getList(currentPage.value, pageSize.value, formInline.name)
      .then(res => {
        console.log(res)
        const msg = res.data.message
        tableData.value = msg.list
        pageTotal.value = msg.total
      })
}
const tableData = ref([])
onMounted(() => {
  search()
})
const insert = () => {
  form.ingredientId = -1
  form.name = ""
  form.img = ""
  form.fragranceNoteId = "1"
  fileList.value = []
  dialogFormVisible.value = true
}
const edit = (row) => {
  form.ingredientId = row.ingredientId
  form.name = row.name
  form.img = row.img
  form.fragranceNoteId = `${row.fragranceNoteId}`
  fileList.value = [{
    name:row.name,
    url:row.img
  }]
  dialogFormVisible.value = true
}
const delVisible = ref(false)
const delDia = (val) => {
  delFlag.value = val
  delVisible.value = true
}
let delFlag = ref(-1)
const removeId = () => {
  if (delFlag.value != -1) {
    delVisible.value = false
    removeOne(delFlag.value)
  }
}

const dialogFormVisible = ref(false)
const formLabelWidth = 120
const form = reactive({
  name: "",
  ingredientId: -1,
  img: "",
  fragranceNoteId: "1",//香调
})
const infoSubmit = () => {
  form.fragranceNoteId = parseInt(form.fragranceNoteId)
  if (form.ingredientId == -1) {
    add(form)
        .then(res => {
          console.log(res)
          if (res.data.success) {
            ElMessage({
              type: 'success',
              message: "新增成功"
            })
          } else {
            ElMessage({
              type: "error",
              message: res.data.message
            })
          }
        })
  } else {
    update(form).then(res => {
      console.log(res)
      if (res.data.success) {
        ElMessage({
          type: 'success',
          message: "更新成功"
        })
      } else {
        ElMessage({
          type: "error",
          message: res.data.message
        })
      }
    })
  }
  search()
  dialogFormVisible.value = false
}
const fragranceList = ref([])
const getFraNote = () => {
  axios.post("/api/fragrance/list")
      .then(res => {
        console.log(res)
        fragranceList.value = res.data.message
      })
}
getFraNote()

import { Plus } from '@element-plus/icons-vue'

import type { UploadProps, UploadUserFile } from 'element-plus'

const fileList = ref<UploadUserFile[]>([
  //  {
  //   name: 'figure-2.png',
  //   url: '/images/figure-2.png',
  // },
])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
  form.img=""
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const tokenBody = {
  token:localStorage.getItem("wikiback-auth-token")
}
const hanleSuccess: UploadProps["onSuccess"] = (res) => {
  console.log(res);
  // form.img.push({
  //   name: res.message,
  //   url: res.message,
  // });
  if(res.success){
    ElMessage({
      type:"success",
      message:"上传成功"
    })
    form.img = res.message
  }else{
    ElMessage({
      type:"error",
      message:"上传失败"
    })
    fileList.value = []
  }
};
</script>

<template>
  <div>
    <el-dialog v-model="dialogFormVisible" title="原料信息" width="500">
      <el-form :model="form">
        <el-form-item :label-width="formLabelWidth" label="原料名称">
          <el-input v-model="form.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="香调类型">
          <el-select-v2
              v-model="form.fragranceNoteId"
              :options="fragranceList"
              placeholder="请选择香调"
              size="large"
              style="width: 240px"
          />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="图片">
          <el-upload
              v-model:file-list="fileList"
              action="/api/upload/img"
              :headers="tokenBody"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="hanleSuccess"
              limit="1"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          为了更好地压缩并展示香水图片，请采用jpg格式上传
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
      </el-form>


      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="infoSubmit">
            {{ form.ingredientId == -1 ? "新增" : "更新" }}
          </el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog
        v-model="delVisible"
        title="提示"
        width="500"
    >
      <span>是否删除该条记录？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="delVisible = false">取消</el-button>
          <el-button type="primary" @click="removeId">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-form :inline="true" :model="formInline" class="demo-form-inline"
             style="display:flex;justify-content: end">
      <el-form-item label="原料名称">
        <el-input v-model="formInline.name" clearable placeholder="请输入原料名称"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button type="primary" @click="insert">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" style="width: 100%;height: 70vh;min-height: 500px">
      <el-table-column prop="ingredientId" width="100"/>
      <el-table-column label="香料名称" prop="name" width="320"/>
      <el-table-column label="图片">
        <template #default="scope">
          <el-image :src="scope.row.img" style="height: 60px">
            <template #error>
              <div class="image-slot">
                <el-icon>
                  <icon-picture/>
                </el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="Operations" min-width="120">
        <template #default="scope">
          <el-button link size="small" type="primary" @click="delDia(scope.row.ingredientId)">
            删除
          </el-button>
          <el-button link size="small" type="primary" @click="edit(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :background="background"
        :disabled="disabled"
        :page-sizes="[20, 40, 60, 80]"
        :size="size"
        :total="pageTotal"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<style lang="scss" scoped>

</style>